package channels

import (
	"fmt"
	"net/smtp"
	"strings"
)

type EmailConfig struct {
	SMTPHost     string
	SMTPPort     string
	SMTPUsername string
	SMTPPassword string
	FromAddress  string
	FromName     string
}

type EmailChannel struct {
	config EmailConfig
}

func NewEmailChannel(config EmailConfig) *EmailChannel {
	return &EmailChannel{config: config}
}

func (e *EmailChannel) Send(recipients []string, subject, body string) error {
	// Set up authentication
	auth := smtp.PlainAuth("", e.config.SMTPUsername, e.config.SMTPPassword, e.config.SMTPHost)

	// Build email message
	from := fmt.Sprintf("%s <%s>", e.config.FromName, e.config.FromAddress)
	msg := e.buildMessage(from, recipients, subject, body)

	// Send email
	addr := fmt.Sprintf("%s:%s", e.config.SMTPHost, e.config.SMTPPort)
	err := smtp.SendMail(addr, auth, e.config.FromAddress, recipients, []byte(msg))
	if err != nil {
		return fmt.Errorf("failed to send email: %w", err)
	}

	return nil
}

func (e *EmailChannel) buildMessage(from string, to []string, subject, body string) string {
	headers := make(map[string]string)
	headers["From"] = from
	headers["To"] = strings.Join(to, ", ")
	headers["Subject"] = subject
	headers["MIME-Version"] = "1.0"
	headers["Content-Type"] = "text/html; charset=UTF-8"

	message := ""
	for k, v := range headers {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + body

	return message
}

func (e *EmailChannel) Name() string {
	return "email"
}
